package com.situ.student.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.situ.student.dao.IStudentDao;
import com.situ.student.dao.impl.StudentDaoJdbcImpl;
import com.situ.student.entity.PageBean;
import com.situ.student.entity.Student;
import com.situ.student.service.IStudentService;

public class StudentServiceImpl implements IStudentService{
	//private IStudentDao studentDao = new StudentDaoMemoryImpl();
	private IStudentDao studentDao = new StudentDaoJdbcImpl();

	@Override
	public boolean insert(Student student) {
		int count = studentDao.insert(student);
		return count == 1 ? true : false;
	}

	@Override
	public List<Student> list() {
		List<Student> list = studentDao.list();
		List<Student> copyList = new ArrayList<>();
		for (Student student : list) {
//			student.setName("Java1807-" + student.getName());
			student.setName(student.getName());
			
			copyList.add(student);
		}
		return copyList;
		//return studentDao.list();
	}

	@Override
	public boolean deleteById(Integer id) {
		int count = studentDao.deleteById(id);
		return count == 1 ? true : false;
	}

	@Override
	public Student findById(Integer id) {
		return studentDao.findById(id);
	}

	@Override
	public boolean update(Student student) {
		int count = studentDao.update(student);
		return count == 1 ? true : false;
	}

	@Override
	public List<Student> findByName(String name) {
		return studentDao.findByName(name);
	}

	@Override
	public PageBean getPageBean(int pageNo, int pageSize) {
		//当前页数
		PageBean pageBean = new PageBean();
		//一页多少数据
		pageBean.setPageNo(pageNo);
		pageBean.setPageSize(pageSize);
		//总记录数
		int totalCount = studentDao.getTotalCount();
		pageBean.setTotalCount(totalCount);
		//一共有多少页
		//总数量   每页数量    总页数
		// 10     3      4       10/3=3...1
		// 11     3      4       10/3=3...2
		// 12     3      4       10/3=4
		// 13     3      5       10/3=4...1
		int totalPage = (int)Math.ceil((double)totalCount/pageSize);
		pageBean.setTotalPage(totalPage);
		//当前页的数据
		int offset = (pageNo - 1) * pageSize;
		List<Student> list =  studentDao.pageList(offset,pageSize);
		pageBean.setList(list);
		return pageBean;
	}

	@Override
	public boolean deleteAll(String[] selectIds) {
		//有缺点：每次打开连接，关闭连接，非常消耗性能
		/*for (String id : selectIds) {
		studentDao.deleteById(Integer.parseInt(id));
		}*/
				
		//批量删除
		int count = studentDao.deleteAll(selectIds);
		return count == selectIds.length ? true : false;
		
	}
}
